﻿CREATE PROCEDURE [dbo].[sp_DomainControllers](@CSVDomainList NVARCHAR(MAX))
AS
BEGIN
	DECLARE @Delimiter NVARCHAR(1)
	SET @Delimiter = ','

	DECLARE @QueryString NVARCHAR(MAX)
	SET @QueryString = ''
	WHILE (Charindex(@Delimiter, @CSVDomainList)>0)
	BEGIN
		SET @QueryString = @QueryString + 'SELECT '''
			+ ltrim(rtrim(Substring(@CSVDomainList,1,Charindex(@Delimiter, @CSVDomainList) - 1)))
			+ ''' As DomainFqdn, * FROM [dbo].[fn_FindAllDomainControllers]('''
			+ ltrim(rtrim(Substring(@CSVDomainList,1,Charindex(@Delimiter, @CSVDomainList) - 1)))
			+ ''') UNION '
		SET @CSVDomainList = Substring(@CSVDomainList, Charindex(@Delimiter, @CSVDomainList) + Len(@Delimiter), Len(@CSVDomainList))
	END
	
	SET @QueryString = @QueryString + 'SELECT '''
		+ ltrim(rtrim(@CSVDomainList))
		+ ''' As DomainFqdn, * FROM [dbo].[fn_FindAllDomainControllers]('''
		+ ltrim(rtrim(@CSVDomainList)) + ''')'
	PRINT @QueryString
	EXEC [sys].[sp_executesql] @QueryString
END
